
import axios from 'axios';
// axios提供的拦截器interceptor
// 拦截请求
axios.interceptors.request.use( async (config) => {
    console.log(config.url,localStorage.getItem("expire_time"));
    console.log(Date.now() , Date.parse(localStorage.getItem("expire_time")) - 10 * 60 * 1000)
    if(config.url != `${url}/users/refreshToken` && localStorage.getItem("expire_time")){
        if(Date.now() > Date.parse(localStorage.getItem("expire_time")) - 10 * 60 * 1000){
            let {data} = await axios({
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                method:"post",
                url:`${url}/users/refreshToken`,
                data:{
                    refreshToken:localStorage.getItem("refresh_token")
                }
            });
        
            if(data.code == 1){
                localStorage.setItem("access_token",data.data.access_token);
                localStorage.setItem("expire_time",data.data.expire_time);
            }
        }
    }
    config.headers['Authorization'] = 'Bearer '+ localStorage.getItem("access_token");
    return config;
});
// 拦截响应
axios.interceptors.response.use((response) => {
    if(response.data.code == 2001 || response.data.code == 2007 || response.data.code == 2009){
        location.href = "/login";
        return;
    }
    return response;
})

export const upload = async(data) => {
    const res = await axios.post(url + "/upload", data, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    return res.data;
}
export const deleteFile = async(file) => {
    const res = await axios({
        method: 'delete',
        url: url + "/deleteFile",
        data: {file}
    });
    return res.data;
}
export const deleteFiles = async(files) => {
    const res = await axios({
        method: 'delete',
        url: url + "/deleteFiles",
        data: {files}
    });
    return res.data;
}
export const cleanFiles = async() => {
    const res = await axios({
        method: 'delete',
        url: url + "/cleanFiles"
    });
    return res.data;
}

let url = "";
if(process.env.NODE_ENV == "development"){
    url = "/api";
}

// const staticUrl = "https://7072-prod-4grqj8ni3f9b5665-1317871699.tcb.qcloud.la/yanbai/";
const staticUrl = "/api/upload/"
export {axios,url,staticUrl};

